<script>
	import Crypto from '@/common/upload/crypto.js';
	import '@/common/upload/hmac.js';
	import '@/common/upload/sha1.js';
	var socketTimer = null;
	let timers = null;
	import {
		Base64
	} from '@/common/upload/base64.js';
	var uploadFileSize = 1024 * 1024 * 100; // 上传文件的大小限制100m
	var policyText = {
		"expiration": "2099-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
		"conditions": [
			["content-length-range", 0, uploadFileSize] // 设置上传文件的大小限制 
		]
	};
	var accessid = "LTAI5tPpTW26Ug49nBPaPM3Z";
	//自己去申请
	var accesskey = "OdnQOjtE27vFtDlLYXqhLPzMIydDLo"
	//自己去申请
	var osshost = 'https://ruomian.oss-cn-chengdu.aliyuncs.com';
	var policyBase64 = Base64.encode(JSON.stringify(policyText));
	var message = policyBase64;
	var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {
		asBytes: true
	});
	var signature = Crypto.util.bytesToBase64(bytes);
	var timetamp = new Date().getTime();

	function random_string(len) {
		len = len || 32;
		var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
		var maxPos = chars.length;
		var pwd = '';
		for (let i = 0; i < len; i++) {
			pwd += chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return pwd;
	}
//   import {cityAllData} from "common/city.js";
	import checkappupdate from 'common/checkappupdate.js';
  import numberJpan from "./components/numberJpan/numberJpan";


//=================================即时通讯引入开始===================================================

  // APP 和 小程序平台
  // #ifdef  APP-PLUS || MP-WEIXIN   
  import TIM from 'tim-wx-sdk';
	import COS from 'cos-wx-sdk-v5';
  // #endif
	
	// #ifdef H5
	import TIM from 'tim-js-sdk';
	import TIMUploadPlugin from 'tim-upload-plugin'
	// logger.error(' TUIKit 暂不支持 H5 / web ，请使用者自己完成兼容哦，页面刷新可能会导致报错，需要重新登录 ');
	// #endif
	
  // #ifdef APP-PLUS
	// import Aegis from 'aegis-weex-sdk';
	// #endif
	
	// #ifdef MP-WEIXIN
	// import Aegis from 'aegis-mp-sdk';
	// #endif
	
	// #ifdef H5
	// import Aegis from 'aegis-web-sdk';
	// #endif
	
	// import logger from './utils/logger'; // app.js
	import {
		genTestUserSig
	} from './debug/GenerateTestUserSig.js';
	import {
		SDKAppID
	} from './debug/GenerateTestUserSig.js';
	
	// const aegis = new Aegis({
	// 	id: 'iHWefAYqKznuxWjLnr', // 项目key
	// 	reportApiSpeed: true, // 接口测速
	// });
	// uni.$aegis = aegis
	// 首先需要通过 uni.requireNativePlugin("ModuleName") 获取 module
	// #ifdef APP-PLUS
	const TUICalling = uni.requireNativePlugin('TUICallingUniPlugin-TUICallingModule');
	// logger.log(`| app |  TUICallingUniPlugin-TUICallingModule | TUICalling: ${TUICalling}`);
	if(typeof(TUICalling) == 'undefined') {
		// logger.error('如果需要音视频功能，请集成原生插件，使用真机运行并且自定义基座调试哦～ 插件地址：https://ext.dcloud.net.cn/plugin?id=7097 , 调试地址：https://nativesupport.dcloud.net.cn/NativePlugin/use/use');
	}
	// #endif

//=================================即时通讯引入结束===================================================


	export default {
		globalData: {
			imgBaseUrl: "https://ruomian.oss-cn-chengdu.aliyuncs.com/",
			phoneReg: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
			videoThumb: "?x-oss-process=video/snapshot,t_0,f_jpg",
			latitude: "",
			// connectUrl: "wss://3020.zhouyangjun.com:8282",
			// connectUrl: "wss://ruo.shanxiyf.com:8282",
			// connectUrl: "",
			longitude: "",
			shareType: "",
			shareProId: "",
			cpid: "", //测评id
			shareid: "", //分享人id
			tgid: "", //团购id
			mdid: "", //门店id
			appSync: {},
			hideFlag: false,
			dxFlag: false,
			pushObj: {},
			updateFlag:false,
			type:"",
			nrid:"",
			//即时通讯开始global中	
				// userInfo: userID userSig token phone
			userInfo: {
				userID:uni.getStorageSync("userId").toString(),
				userSig:genTestUserSig(uni.getStorageSync("userId").toString()).userSig
			},
			expiresIn:"",
			// 个人信息
			userProfile: null,
			isTUIKit: true,
			headerHeight: 0,
			statusBarHeight: 0,
			SDKAppID: genTestUserSig('').sdkAppID,
			//即时通讯结束global中	,
			cityAllData:[]
		},
		onLaunch: function(options) {
      // #ifdef APP
      // 获取cid
      plus.push.getClientInfoAsync(res => {
        this.globalData.pushObj = res;
      });
      //#endif


		  /**==========================APP推送开始============================**/
    //#ifdef APP-PLUS
      let timer = false;
      // let platform = uni.getSystemInfoSync().platform;
      plus.push.addEventListener("click",(msg)=>{
          //导入个推原生类
          // var GeTuiSdk = plus.ios.importClass('GeTuiSdk');
          // GeTuiSdk.setBadge(0);
        clearTimeout(timer);
        timer = setTimeout(()=>{
          plus.runtime.setBadgeNumber(0);
          if(msg.payload){
            uni.navigateTo({
              url:msg.payload
            })
          }
        },1500)
        // plus.push.clear();
      },false)
      plus.push.addEventListener("receive",(msg)=>{
        if (msg.type == "receive") // 这里判断触发的来源，否则一直推送。
        {
          if (platform == 'ios') {
            console.log(msg.payload)
            plus.push.createMessage(
                msg.payload.content,
                //本地创建通知payload只能传string，否则无法成功传递（为null）
                JSON.stringify(msg.payload), {
                  cover: false,
                  title: msg.title,
                });
          }
        }
        if("LocalMSG" == msg.payload){
        }else{
          if(msg.type=='receive'){
            var options = {cover:false,title:msg.title};
            plus.push.createMessage(msg.content, msg.payload, options );
          }
        }
      },false)
      //#endif
      /**==========================APP推送结束============================**/
      // #ifdef MP-WEIXIN
			if (options.query.shareid) {
				this.globalData.shareid = options.query.shareid;
			}
			if (options.query.cpid) {
				this.globalData.cpid = options.query.cpid;
			}
			if (options.query.tgid) {
				this.globalData.tgid = options.query.tgid;
			}
			if (options.query.mdid) {
				this.globalData.mdid = options.query.mdid;
			}
			// if (options.query.q) {
			// 	let q = decodeURIComponent(options.query.q);
			// 	if (q.indexOf("?") != -1) {
			// 		if (this.getArgs(q, "shareid")) {
			// 			this.globalData.shareid = this.getArgs(q, "shareid");
			// 		}
			// 		if (this.getArgs(q, "cpid")) {
			// 			this.globalData.cpid = this.getArgs(q, "cpid");
			// 		}
			// 		if (this.getArgs(q, "tgid")) {
			// 			this.globalData.tgid = this.getArgs(q, "tgid");
			// 		}
			// 		if (this.getArgs(q, "mdid")) {
			// 			this.globalData.mdid = this.getArgs(q, "mdid");
			// 		}
			// 		let type = this.getArgs(q, "type");
			// 		if(type=='cp'){
			// 			uni.navigateTo({
			// 				url:"/pages/pageone/pages/ActivityDetails/ActivityDetails?id="+this.globalData.cpid
			// 			})
			// 		}
			// 		if(type=='tg'){
			// 			uni.navigateTo({
			// 				url:"/pages/pagethree/pages/OfferDetails/OfferDetails?id="+this.globalData.tgid
			// 			})
			// 		}
			// 		if(type=='tpnr'){
			// 			uni.navigateTo({
			// 				url:"/pages/pagetwo/pages/FindDetail/FindDetail?id="+this.getArgs(q, "nrid")
			// 			})
			// 		}
			// 		if(type=='spnr'){
			// 			uni.navigateTo({
			// 				url:"/pages/pagefive/pages/VideoDetail/VideoDetail?id="+this.getArgs(q, "nrid")
			// 			})
			// 		}
			// 		if(type=='gr'){
			// 			uni.navigateTo({
			// 				url:"/pages/pageone/pages/Business-card/Business-card?id="+this.getArgs(q, "usid")
			// 			})
			// 		}
			// 	}
			// }
			// #endif
			// #ifdef APP
			checkappupdate.check({
				title: '检测到有新版本！',
				content: '请升级app到最新版本！',
				canceltext: '暂不升级',
				oktext: '立即升级'
			});
			var args = plus.runtime.arguments;
			if (args) {

				// 处理args参数，如直达到某新页面等  
				let q = args;
				if (q.indexOf("?") != -1) {
					if (this.getArgs(q, "shareid")) {
						this.globalData.shareid = this.getArgs(q, "shareid");
					}
					if (this.getArgs(q, "cpid")) {
						this.globalData.cpid = this.getArgs(q, "cpid");
					}
					if (this.getArgs(q, "tgid")) {
						this.globalData.tgid = this.getArgs(q, "tgid");
					}
					if (this.getArgs(q, "mdid")) {
						this.globalData.mdid = this.getArgs(q, "mdid");
					}
					let type = this.getArgs(q, "type");
					this.globalData.type = this.getArgs(q, "mdid");
					if (type == 'cp') {
						uni.navigateTo({
							url: "/pages/pageone/pages/ActivityDetails/ActivityDetails?id=" + this.globalData
								.cpid
						})
					}
					if (type == 'tg') {
						uni.navigateTo({
							url: "/pages/pagethree/pages/OfferDetails/OfferDetails?id=" + this.globalData.tgid
						})
					}
					if (type == 'tpnr') {
						this.globalData.nrid = this.getArgs(q, "nrid");
						uni.navigateTo({
							url: "/pages/pagetwo/pages/FindDetail/FindDetail?id=" + this.getArgs(q, "nrid")
						})
					}
					if (type == 'spnr') {
						this.globalData.nrid = this.getArgs(q, "nrid");
						uni.navigateTo({
							url: "/pages/pagefive/pages/VideoDetail/VideoDetail?id=" + this.getArgs(q, "nrid")
						})
					}
					if (type == 'gr') {
						uni.navigateTo({
							url: "/pages/pageone/pages/Business-card/Business-card?id=" + this.getArgs(q,
								"usid")
						})
					}
				}
			}
			// #endif
			if (uni.getStorageSync("rmToken")) {
				this.createConnect();
				this.sendMessage({
					"contacts": 2
				});
				if (this.globalData.latitude) {
					let posObj = {};
					posObj.dimension = this.globalData.latitude;
					posObj.longitude = this.globalData.longitude;
					this.sendMessage(posObj)
				} else {
					this.indexInitFun().then(res => {
						let posObj = {};
						posObj.dimension = this.globalData.latitude;
						posObj.longitude = this.globalData.longitude;
						// posObj.longitude = uni.getStorageSync("longitude");//117.082094;;
						// posObj.dimension = uni.getStorageSync("latitude");//39.987725;
						this.sendMessage(posObj)
					})
				}
			}
			if (uni.getStorageSync("rmToken") && this.globalData.dxFlag) {
				this.createConnect();
				this.sendMessage({
					"contacts": 2
				});
				if (this.globalData.latitude) {
					let posObj = {};
					posObj.dimension = this.globalData.latitude;
					posObj.longitude = this.globalData.longitude;
					// posObj.longitude = uni.getStorageSync("longitude");//117.082094;;
					// posObj.dimension = uni.getStorageSync("latitude");//39.987725;
					this.sendMessage(posObj)
				} else {
					this.indexInitFun().then(res => {
						let posObj = {};
						posObj.dimension = this.globalData.latitude;
						posObj.longitude = this.globalData.longitude;
						// posObj.longitude = uni.getStorageSync("longitude");//117.082094;;
						// posObj.dimension = uni.getStorageSync("latitude");//39.987725;
						this.sendMessage(posObj)
					})
				}
			}
			// let that = this;
			// uni.getLocation({
			//     type: 'wgs84',
			//     success: function (res) {

			// 				that.longitude = res.longitude
			// 				that.latitude = res.latitude
			// 				alert(res.longitude,res.latitude)
			//     }
			// })
		// ==================================即时通讯开始Onlunch中开始=============================
			const SDKAppID = genTestUserSig('').sdkAppID;
			// uni.$aegis.reportEvent({
			// 		name: 'onLaunch',
			// 		ext1: 'onLaunch-success',
			// 		ext2: 'uniTuikitExternal',
			// 		ext3: `${SDKAppID}`,
			// })
			uni.setStorageSync(`TIM_${SDKAppID}_isTUIKit`, true);
			// 重点注意： 为了 uni-app 更好地接入使用 tim，快速定位和解决问题，请勿修改 uni.$TUIKit 命名。
			// 如果您已经接入 tim ，请将 uni.tim 修改为 uni.$TUIKit。
			uni.$TUIKit = TIM.create({
				SDKAppID: 1400742376
			});
			// #ifndef H5
			uni.$TUIKit.registerPlugin({
				'cos-wx-sdk': COS
			});
			// #endif
			
			// #ifdef H5
			uni.$TUIKit.registerPlugin({ 
				'tim-upload-plugin':TIMUploadPlugin,
				'cos-wx-sdk': COS,
			})
			// #endif
			// 将原生插件挂载在 uni 上
			// #ifdef APP-PLUS
			uni.$TUICalling = TUICalling;
			// #endif
			// 如果您已创建了 tim，请将 tim 实例挂载在 wx 上，且不可以修改 wx.$TIM（修改变量可能导致 TUICalling 组件无法正常使用）, 完成 TUICalling 初始化，
			// 如果您没有创建，可以不传
			// #ifdef MP-WEIXIN
			wx.$TIM = uni.$TUIKit;
			// #endif
			uni.$TUIKitTIM = TIM;
			uni.$TUIKitEvent = TIM.EVENT;
			uni.$TUIKitVersion = TIM.VERSION;
			uni.$TUIKitTypes = TIM.TYPES; // 监听系统级事件
			uni.$TUIKit.on(uni.$TUIKitEvent.SDK_READY, this.onSDKReady);
			uni.$TUIKit.on(uni.$TUIKitEvent.SDK_NOT_READY, this.onSdkNotReady);
			uni.$TUIKit.on(uni.$TUIKitEvent.KICKED_OUT, this.onKickedOut);
			uni.$TUIKit.on(uni.$TUIKitEvent.ERROR, this.onTIMError);
			uni.$TUIKit.on(uni.$TUIKitEvent.NET_STATE_CHANGE, this.onNetStateChange);
			uni.$TUIKit.on(uni.$TUIKitEvent.SDK_RELOAD, this.onSDKReload);
			uni.$resetLoginData = this.resetLoginData();

			//重新设置用户信息
			uni.$LTLogin = this.liaotianLogin();
			uni.$LTUpdateMyInfo = this.ltUpdateMyInfo();
		// ==================================即时通讯开始Onlunch中结束=============================
		},
		onShow: function() {

			//调用城市接口
			this.getAllCityDataMethod();
			// this.globalData.hideFlag = false;
			clearTimeout(timers)
			// #ifdef APP
			// 推送信息
			plus.push.getClientInfoAsync(res => {

				this.globalData.pushObj = res;
			}, err => {

			});
			// 
			var args = plus.runtime.arguments;
			if (args) {

				// 处理args参数，如直达到某新页面等  
				let q = args;
				if (q.indexOf("?") != -1) {
					if (this.getArgs(q, "shareid")) {
						this.globalData.shareid = this.getArgs(q, "shareid");
					}
					if (this.getArgs(q, "cpid")) {
						this.globalData.cpid = this.getArgs(q, "cpid");
					}
					if (this.getArgs(q, "tgid")) {
						this.globalData.tgid = this.getArgs(q, "tgid");
					}
					if (this.getArgs(q, "mdid")) {
						this.globalData.mdid = this.getArgs(q, "mdid");
					}
					let type = this.getArgs(q, "type");
					if (type == 'cp') {
						uni.navigateTo({
							url: "/pages/pageone/pages/ActivityDetails/ActivityDetails?id=" + this.globalData
								.cpid
						})
					}
					if (type == 'tg') {
						uni.navigateTo({
							url: "/pages/pagethree/pages/OfferDetails/OfferDetails?id=" + this.globalData.tgid
						})
					}
					if (type == 'tpnr') {
						uni.navigateTo({
							url: "/pages/pagetwo/pages/FindDetail/FindDetail?id=" + this.getArgs(q, "nrid")
						})
					}
					if (type == 'spnr') {
						uni.navigateTo({
							url: "/pages/pagefive/pages/VideoDetail/VideoDetail?id=" + this.getArgs(q, "nrid")
						})
					}
					if (type == 'gr') {
						uni.navigateTo({
							url: "/pages/pageone/pages/Business-card/Business-card?id=" + this.getArgs(q,
								"usid")
						})
					}
				}
			}
			// #endif
			
			this.$u.api.commonDetails({
				name: "service_charge_percentage"
			}).then(res => {
				this.globalData.appSync = res.data.details;
			})
		},
		onHide: function() {

			this.globalData.hideFlag = true;
			timers = setTimeout(() => {
				uni.closeSocket({
					reason: "khdClose"
				})
			}, 60000)
		},
		methods: {
		  //获取城市信息
	getAllCityDataMethod(){
		this.$u.api.getCityAllData({}).then(res => {
				this.cityAllData = res.list;
		})
	},
      getCity() {
        if (!uni.getStorageSync("cityStr")) {
          return false;
        }
        if (!uni.getStorageSync("cityData")) {
          let cityAllData = this.cityAllData;
          for (let i = 0; i < cityAllData.length; i++) {
            if (cityAllData[i].name.indexOf(uni.getStorageSync("cityStr")) != -1) {
              this.cityObj = cityAllData[i];
              this.cityObj.id = cityAllData[i].id;
              this.cityObj.name = cityAllData[i].name;
              uni.setStorageSync("cityData", this.cityObj)
            }
          }
          this.getArea();
          this.getList();
        }
      },
			toLogin(){
				// #ifdef MP-WEIXIN
				uni.navigateTo({
				url:"/pages/pagefive/pages/wxLogin/wxLogin"
				})
				// #endif
				// #ifdef APP-PLUS
				uni.navigateTo({
				url:"/pages/pagethree/pages/Login/Login"
				})
				// #endif
				// #ifdef MP-TOUTIAO
				uni.navigateTo({
				url:"/pages/pagethree/pages/Login/Login"
				})
				// #endif
			},
			setBadge(num){
				// #ifdef APP
				plus.runtime.setBadgeNumber(num);
				// #endif
			},
			clearBadge(){
				// #ifdef APP
				plus.runtime.setBadgeNumber(0);
				// #endif
			},
			loadMsg() {
				return false;
				return new Promise((resolve, reject) => {
					let _this = this;
					uni.connectSocket({
						url: _this.globalData.connectUrl,
						success: res => {
							
						}
					});
					uni.onSocketOpen(function(res) {
						_this.globalData.hideFlag = false;
						_this.globalData.dxFlag = false;
						resolve();
						_this.sendMessage({
							connect: "keep connected"
						});
						if (uni.getStorageSync("rmToken")) {
							_this.sendMessage({
								"contacts": 2
							});
						}
						if (_this.globalData.latitude) {
							let posObj = {};
							posObj.dimension = _this.globalData.latitude;
							posObj.longitude = _this.globalData.longitude;
							// posObj.longitude = uni.getStorageSync("longitude");//117.082094;;
							// posObj.dimension = uni.getStorageSync("latitude");//39.987725;
							_this.sendMessage(posObj)
						} else {
							_this.indexInitFun().then(res => {
								let posObj = {};
								posObj.dimension = _this.globalData.latitude;
								posObj.longitude = _this.globalData.longitude;
								// posObj.longitude = uni.getStorageSync("longitude");//117.082094;;
								// posObj.dimension = uni.getStorageSync("latitude");//39.987725;
								_this.sendMessage(posObj)
							})
						}
						// socketTimer = setInterval(() => {
						// 	_this.sendMessage({
						// 		connect: "keep connected"
						// 	});
						// }, 30000)
					});
					uni.onSocketMessage(function(res) {

						if (res.data == 'khdClose') {
							_this.globalData.dxFlag = true;
						} else {
							let data = JSON.parse(res.data);
							if (data.state == 2 && data.num > 0) {
								_this.globalData.msgNum = data.num;
								uni.setTabBarBadge({
									index: 2,
									text: _this.globalData.msgNum.toString()
								});
								_this.setBadge(Number(_this.globalData.msgNum));
							} else if (data.state == 2 && data.num == 0) {
								_this.globalData.msgNum = data.num;
								uni.hideTabBarRedDot({
									index: 2
								})
								_this.clearBadge();
							}
							if (data.vice_user_id == uni.getStorageSync("userId")) {
								_this.globalData.msgNum = Number(_this.globalData.msgNum) + 1;
								uni.setTabBarBadge({
									index: 2,
									text: _this.globalData.msgNum.toString()
								});
								_this.setBadge(Number(_this.globalData.msgNum));
							}
						}
					
					});
					uni.onSocketError(function(res) {

					});
					uni.onSocketClose(function(res) {

						_this.globalData.dxFlag = true;
						if (res.reason == 'khdClose') {
							
						} else {
							uni.connectSocket({
								url: _this.globalData.connectUrl,
								success: res => {

									_this.globalData.dxFlag = false;
								}
							});
						}
					})
				})
			},
			getArgs(url, name) {
				let str = url.split("?")[1];
				let arr = str.split("&");
				let obj = {};
				for (let i = 0; i < arr.length; i++) {
					obj[arr[i].split("=")[0]] = arr[i].split("=")[1];
				}
				return obj[name];
			},
			sendMessage(data) {
				data.token = uni.getStorageSync("rmToken");
				data = JSON.stringify(data);

				uni.sendSocketMessage({
					data
				})
			},
			createConnect() {
				return false;
				this.$u.api.labelList({
					type: 5,
					page: 1,
					limit: 1
				}).then(res => {
					let _this = this;
					uni.connectSocket({
						url: _this.globalData.connectUrl,
						success: res => {

							_this.globalData.dxFlag = false;
						}
					});
					uni.onSocketOpen(function(res) {
						_this.globalData.hideFlag = false;
						_this.sendMessage({
							connect: "keep connected"
						});
						if (uni.getStorageSync("rmToken")) {
							_this.sendMessage({
								"contacts": 2
							});
						}
						if (_this.globalData.latitude) {
							let posObj = {};
							posObj.dimension = _this.globalData.latitude;
							posObj.longitude = _this.globalData.longitude;
							// posObj.longitude = uni.getStorageSync("longitude");//117.082094;;
							// posObj.dimension = uni.getStorageSync("latitude");//39.987725;
							_this.sendMessage(posObj)
						} else {
							_this.indexInitFun().then(res => {
								let posObj = {};
								posObj.dimension = _this.globalData.latitude;
								posObj.longitude = _this.globalData.longitude;
								// posObj.longitude = uni.getStorageSync("longitude");//117.082094;;
								// posObj.dimension = uni.getStorageSync("latitude");//39.987725;
								_this.sendMessage(posObj)
							})
						}
						socketTimer = setInterval(() => {
							_this.sendMessage({
								connect: "keep connected"
							});
						}, 30000)
					});
					uni.onSocketMessage(function(res) {
						if (res.data == 'khdClose') {
							_this.globalData.dxFlag = true;
						} else {
							let data = JSON.parse(res.data);
							if (data.state == 2 && data.num > 0) {
								_this.globalData.msgNum = data.num;
								uni.setTabBarBadge({
									index: 2,
									text: _this.globalData.msgNum.toString()
								});
								_this.setBadge(Number(_this.globalData.msgNum));
							} else if (data.state == 2 && data.num == 0) {
								_this.globalData.msgNum = data.num;
								uni.hideTabBarRedDot({
									index: 2
								})
								_this.clearBadge();
							}
							if (data.vice_user_id == uni.getStorageSync("userId")) {
								_this.globalData.msgNum = Number(_this.globalData.msgNum) + 1;
								uni.setTabBarBadge({
									index: 2,
									text: _this.globalData.msgNum.toString()
								});
								_this.setBadge(Number(_this.globalData.msgNum));
							}
						}

					});
					uni.onSocketError(function(res) {

					});
					uni.onSocketClose(function(res) {

						_this.globalData.dxFlag = true;
						if (_this.globalData.hideFlag) {
							
						} else {
							uni.connectSocket({
								url: _this.globalData.connectUrl,
								success: res => {

									_this.globalData.dxFlag = false;
								}
							});
						}
					})
				})
			},
			checkAuth(type) {
				return new Promise((resolve, reject) => {
					uni.getSetting({
						success: res => {
							if (res.authSetting[type] != undefined && res.authSetting[type] != true) {
								resolve(false)
							} else {
								resolve(true)
							}
						}
					})
				})
			},
			//检查是否授权
			checkGetLaction() {
				var that = this;
				uni.getSetting({
					success(res) {
						if (res.authSetting['scope.userLocation'] != undefined && res.authSetting[
								'scope.userLocation'] != true) {
							uni.showModal({
								title: '是否授权当前位置',
								content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
								success: function(res) {
									if (res.cancel) {

										that.globalData.latitude = -48.526;
										that.globalData.longitude = -123.236;
									} else if (res.confirm) {

										uni.openSetting({
											success: function(data) {

												if (data.authSetting[
														"scope.userLocation"] == true) {
													uni.showToast({
														title: '授权成功',
														icon: 'success',
														duration: 2000
													})
													that.getLocation()

												} else {
													uni.showToast({
														title: '授权失败',
														icon: 'success',
														duration: 5000
													})
												}
											}
										})
									}
								},
								fail: err => {

								}
							})
						}
					}
				})
			},
			isImage(ext) {
				var index = ext.lastIndexOf(".");
				//获取后缀
				var urls = ext.substr(index + 1);
				return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(urls.toLowerCase()) !== -
					1;
			},
			getImgBase(url) {
				// #ifdef APP
				return new Promise((resolve, reject) => {
					let toBase64Url;
					uni.request({
						url: url,
						method: 'GET',
						responseType: "arraybuffer",
						success: res => {

							let base64 = uni.arrayBufferToBase64(res.data); //把arraybuffer转成base64
							toBase64Url = 'data:image/jpeg;base64,' + base64; //不加上这串字符，在页面无法显示
							resolve(toBase64Url);
						}
					});
				})
				// #endif
				// #ifdef MP-WEIXIN

				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: url,
						success: res => {
							resolve(res.path);
						}
					})
				})
				// #endif
			},
			indexInitFun() {
				// #ifdef MP-WEIXIN
				return new Promise((resolve, reject) => {
					uni.onLocationChange((result) => {

						this.globalData.latitude = result.latitude;
						this.globalData.longitude = result.longitude;
            let nowTime = Date.parse(new Date()) / 1000;
            uni.setStorageSync("mathlat",result.latitude+'|'+ Number(nowTime + 6000));
            uni.setStorageSync("longitude",result.longitude);
            uni.setStorageSync("latitude",result.latitude);
						resolve(result)
					})
					uni.onLocationChangeError(err => {

						reject()
					})
				})
				// #endif
				// #ifdef APP

				return new Promise((resolve, reject) => {
					uni.getLocation({
						type: "gcj02",
						success: result => {
              let nowTime = Date.parse(new Date()) / 1000;
              uni.setStorageSync("mathlat",result.latitude+'|'+ Number(nowTime + 6000));
              uni.setStorageSync("longitude",result.longitude);
              uni.setStorageSync("latitude",result.latitude);
							this.globalData.latitude = result.latitude;
							this.globalData.longitude = result.longitude;

							resolve(result)
						},
						fail: err => {
							reject()
						}
					})
				})
				// #endif
			},
			getCateList() {
				return new Promise((resolve, reject) => {
					this.$u.api.industryList().then(res => {
						resolve(res)
					})
				})
			},
			getContentDetail(datas, type) {
				return new Promise((resolve, reject) => {
					if (type == "videoDetail") {

						if (uni.getStorageSync("rmToken")) {
							this.$u.api.shareDetails(datas).then(res => {
								resolve(res)
							})
						} else {
							this.$u.api.indexShareDetails(datas).then(res => {
								resolve(res)
							})
						}
					} else if (type == "commentList") {
						this.$u.api.shareCommentList(datas).then(res => {
							resolve(res)
						})
					} else if (type == "replyList") {
						this.$u.api.shareCommentReplyList(datas).then(res => {
							resolve(res)
						})
					} else if (type == "replyAdd") {
						this.$u.api.shareCommentReplyAdd(datas).then(res => {
							uni.showToast({
								icon: 'none',
								title: "回复成功",
								duration: 2000
							})
							resolve(res)
						})
					} else if (type == "commentAdd") {
						this.$u.api.shareCommentAdd(datas).then(res => {
							uni.showToast({
								icon: 'none',
								title: "评论成功",
								duration: 2000
							})
							resolve(res)
						})
					} else if (type == "cancelCollect") {
						this.$u.api.userShareCollectionDel(datas).then(res => {
							uni.showToast({
								icon: 'none',
								title: "已取消收藏",
								duration: 2000
							})
							resolve(res)
						})
					} else if (type == "collectAdd") {

						this.$u.api.userShareCollectionAdd(datas).then(res => {
							uni.showToast({
								icon: 'none',
								title: "已收藏",
								duration: 2000
							})

							resolve(res)
						})
					} else if (type == "giveCommentMain") {
						this.$u.api.shareCommentFabulousAdd(datas).then(res => {
							resolve(res)
						})
					} else if (type == "giveCommentSon") {
						this.$u.api.shareCommentReplyFabulousAdd(datas).then(res => {
							resolve(res)
						})
					} else if (type == "jbFun") {
						this.$u.api.shareReportAdd({
							data: datas
						}).then(res => {
							uni.showToast({
								icon: 'none',
								title: "举报成功",
								duration: 2000
							})
							resolve(res)
						})
					}
				})
			},
			getLocation() {
				let that = this;
				// #ifdef MP-WEIXIN
				uni.getLocation({
					success: res => {
            let nowTime = Date.parse(new Date()) / 1000;
            uni.setStorageSync("mathlat",res.latitude+'|'+ Number(nowTime + 6000));
            uni.setStorageSync("longitude",res.longitude);
            uni.setStorageSync("latitude",res.latitude);
            this.getAreaMethod();
						// uni.startLocationUpdate({
						// 	type: "gcj02",
						// 	success: (res) => {

						// 		uni.onLocationChange((result) => {

						// 			this.globalData.latitude = result.latitude;
						// 			this.globalData.longitude = result.longitude;

						// 		})
						// 		uni.onLocationChangeError(err => {

						// 		})
						// 	},
						// 	fail: (err) => {

						// 		this.checkGetLaction();
						// 	}
						// })
					},
					fail: err => {
						if (err.errMsg == 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF') {
							uni.showModal({
								content: "您未打开GPS定位或GPS信号弱，请调整后点击确认",
								success: rel => {
									if (rel.confirm) {
										that.getLocation();
									}
								}
							})
						}
						this.checkGetLaction()
					}
				})
				// #endif
				// #ifdef APP
				uni.getLocation({
					type: "gcj02",
					success: result => {
            let nowTime = Date.parse(new Date()) / 1000;
            uni.setStorageSync("mathlat",result.latitude+'|'+ Number(nowTime + 6000));
            uni.setStorageSync("longitude",result.longitude);
            uni.setStorageSync("latitude",result.latitude);
            this.getAreaMethod();
						this.globalData.latitude = result.latitude;
						this.globalData.longitude = result.longitude;
					},
					fail: err => {
						//先设置默认值,
						let nowTime = Date.parse(new Date()) / 1000;
            uni.setStorageSync("mathlat",39.916927+'|'+ Number(nowTime + 6000));
            uni.setStorageSync("longitude",116.405419);
            uni.setStorageSync("latitude",39.916927);
            this.getAreaMethod();return;
						uni.showModal({
							content: "请检查手机定位是否开启并且授权给软件后重试！",
							success: rel => {
								if (rel.confirm) {
									this.getLocation();
								}
							}
						})
					}
				})
				// setInterval(() => {
				// 	uni.getLocation({
				// 		type: "gcj02",
				// 		success: result => {
				// 			this.globalData.latitude = result.latitude;
				// 			this.globalData.longitude = result.longitude;

				// 		}
				// 	})
				// }, 60000)
				// #endif
			},
			getTime(time, desc, type) {
				let dates = new Date(time);
				let year = dates.getFullYear();
				let month = (dates.getMonth() + 1) > 9 ? (dates.getMonth() + 1) : '0' + (dates.getMonth() + 1);
				let day = dates.getDate() > 9 ? dates.getDate() : '0' + dates.getDate();
				let hour = dates.getHours() > 9 ? dates.getHours() : '0' + dates.getHours();
				let min = dates.getMinutes() > 9 ? dates.getMinutes() : '0' + dates.getMinutes();
				let sec = dates.getSeconds() > 9 ? dates.getSeconds() : '0' + dates.getSeconds();
				if (type == 'day') {
					return year + desc + month + desc + day;
				} else {
					return year + desc + month + desc + day + ' ' + hour + ":" + min + ":" + sec;
				}
			},
      //判断缓存是否过期
      setLongitudeAndLatitudeTime(){
          let latitude = uni.getStorageSync("mathlat");
          if(latitude){
            let nowTime = Date.parse(new Date()) / 1000;
            // 缓存存在，判断是否过期
            let temp = latitude.split('|');
            if (!temp[1] || Number(temp[1]-nowTime) <= 120) {
              this.getLocation();
            }
            this.getAreaMethod();
          }else{
            this.getLocation();
            this.getAreaMethod();
          }
      },
      getAreaMethod(){
        if(!uni.getStorageSync("latitude")){
          return false;
        }
        this.$u.api.addressAnalysis({str:uni.getStorageSync("latitude")+","+uni.getStorageSync("longitude")}).then(res=>{
          let cityStr = res.data.address_component.city;
          uni.setStorageSync("cityStr",cityStr)
          this.getCity();
        })
      },

			Rad(d) {
				//根据经纬度判断距离
				return d * Math.PI / 180.0;
			},
			getDistance(lat2, lng2) {
				var radLat1 = this.Rad(this.globalData.latitude);
				var radLat2 = this.Rad(lat2);
				var a = radLat1 - radLat2;
				var b = this.Rad(this.globalData.longitude) - this.Rad(lng2);
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math
					.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137;
				s = Math.round(s * 10000) / 10000;
				s = s.toFixed(1); //保留两位小数

				return Number(s);
			},
			updataAvator(urls) {
				return new Promise((resolve, reject) => {
					let pos = urls.lastIndexOf('.');
					let filename = urls.substring(0, pos) // 文件名
					let extendName = urls.substring(pos + 1); // 扩展名
					let stroeAs = '' + timetamp + random_string(5) + '.' + extendName;
					if(extendName.toLocaleLowerCase() == "heic"){
						reject("不支持此格式的图片");
						return false;
					}
					uni.uploadFile({
						url: osshost,
						filePath: urls,
						fileType: 'image',
						name: 'file',
						formData: {
							'key': stroeAs,
							'policy': policyBase64,
							'OSSAccessKeyId': accessid,
							'success_action_status': '200', //让服务端返回200,不然，默认会返回204
							'signature': signature,
						},
						success(res) {
							resolve(stroeAs)
							// that.headimgurl = osshost + '/' + stroeAs;
						},
						fail(err) {
							reject(err)
						}
					})
				})

			},
			//============================即时通讯method中开始=============================
			// TODO:
			// onSDKReady({name}) {
			// 	  const isSDKReady = name === uni.$TUIKitEvent.SDK_READY ? true : false
			// 		uni.$emit('isSDKReady', {
			// 			isSDKReady: true
			// 		});
			// },


			onTIMError(event) {

			uni.showModal({
				title:"温馨提示",
				// content:'初始化聊天错误：' + event.data.code + "," + event.data.message,
				content:'该用户未登录状态!',
			})
		},
		onSDKReady({name}) {

			const isSDKReady = name === uni.$TUIKitEvent.SDK_READY ? true : false
			this.globalData.isSDKReady = true
			this.ltUpdateMyInfo()
		},
		onSdkNotReady() {

			this.globalData.isSDKReady = false
		},
		onNetStateChange(event) {

			// v2.5.0 起支持
				// event.data.state 当前网络状态，枚举值及说明如下：
				// TIM.TYPES.NET_STATE_CONNECTED - 已接入网络
				// TIM.TYPES.NET_STATE_CONNECTING - 连接中。很可能遇到网络抖动，SDK 在重试。接入侧可根据此状态提示“当前网络不稳定”或“连接中”
				// TIM.TYPES.NET_STATE_DISCONNECTED - 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试，若用户网络恢复，SDK 会自动同步消息
				
		},
		onSDKReload() {

		},
		onKickedOut() {

			uni.showModal({
				title:"系统提示",
				content:'您的聊天账号在另一台设备登陆,若不是本人，请联系管理员',
			})
			
			
		},
      liaotianLogin(event) {
        this.resetLoginData();
        this.ltUpdateMyInfo();
        if (!uni.getStorageSync("userId")) {
          return false;
        }
        if (this.globalData.isSDKReady === true) {
          if (this.isNotNull(event)) {
            event(true)
          }
          return
        }
        let usigndata = {
          userID: uni.getStorageSync("userId").toString(),
          userSig: genTestUserSig(uni.getStorageSync("userId").toString()).userSig
        }
        uni.$TUIKit.login(usigndata).then((imResponse) => {
          if (imResponse.data.repeatLogin === true) {
            // 标识帐号已登录，本次登录操作为重复登录。v2.5.1 起支持
          } else {
            let interval = setInterval(() => {
              if (this.globalData.isSDKReady === true) {
                if (this.isNotNull(event)) {
                  clearInterval(interval)
                  event(true)
                }
              }
            }, 500)
          }
        })
            .catch((imError) => {
              uni.showModal({
                title: "系统提示",
                content: "聊天登陆失败，请稍后重试",
              })
              event(false)
            });
      },
      loginout(){
        let promise =  uni.$TUIKit.logout();
        promise.then(function(imResponse) {
         // 登出成功
        }).catch(function(imError) {
          console.warn('logout error:', imError);
        });
      },
		// 聊天 - 初始化数据
		resetLoginData() {
			//从数据库获取到用户信息
      if(!uni.getStorageSync("userId")){
        return false;
      }
			this.$u.api.userDetails({user_id:uni.getStorageSync("userId")}).then(res=>{
					let userdetail = res.data;
			let userInfo = {
				fbNickName:userdetail.username,//"闫伟",
				fbAvatarUrl:userdetail.image_url,//"https://thirdwx.qlogo.cn/mmopen/vi_32/LWicoUend7QOfiabWDRjfpPDB51LzhbzVzjibicqDD2ztqy7BlpicRn8HToMoDVg9g1XfNiayHStXfC2f6yGNHgLueEw/132",
				liaotianId:userdetail.id//"1880",
			}
			this.globalData.expiresIn = '';
			this.globalData.sessionID = '';
			this.globalData.userInfo = {
				userID: userInfo.liaotianId,
				userSig: genTestUserSig(userInfo.liaotianId).userSig,
			};
			this.globalData.userProfile = {
				userID:userInfo.liaotianId,
				nick: userInfo.fbNickName,
				avatar:userInfo.fbAvatarUrl
			};
		})
		},
		ltUpdateMyInfo(){
			if(this.globalData.isSDKReady === true){
        if(!uni.getStorageSync("userId")){
          return false;
        }
				this.$u.api.userDetails({user_id:uni.getStorageSync("userId")}).then(res=>{
					let userdetail = res.data;
					let userInfo = {
					fbNickName:userdetail.username,
					fbAvatarUrl:userdetail.image_url
				}//this.$user.getUserInfo()
				// 修改个人标配资料
        //   let promise = {};

				// let promise = uni.$TIM.updateMyProfile({
				// 	nick: userInfo.fbNickName,
				// 	avatar: userInfo.fbAvatarUrl,
				// 	// allowType: uni.$TIM.TYPES.ALLOW_TYPE_ALLOW_ANY
				// });

          let promise = uni.$TUIKit.updateMyProfile({
            nick: userInfo.fbNickName,
            avatar: userInfo.fbAvatarUrl,
            // allowType: uni.$TIM.TYPES.ALLOW_TYPE_ALLOW_ANY
          });
				promise.then(function(imResponse) {
				}).catch(function(imError) {
				});
				})
			
			}
		},
		/**
		 * 是否不为空
		 * @param {Object} params
		 */
		isNotNull(params){
				if (typeof(params) === 'undefined'){
					return false
				}else if(params == null){
					return false
				}
				
				return true
		},
    sendPushMes(obj) {
      let arr = {};
      arr.user_id = obj.user_id;
      arr.title = obj.title;
      arr.content = obj.content;
      arr.payload = obj.payload;//"/pages/pagethree/pages/myCreation/myCreation?form=shop&type=0";
      this.$u.api.appMessagePush(arr).then(res => {
        console.log(res)
      })
    }


		}
	}
</script>

<style lang="scss">
	@import "uview-ui/index.scss";
</style>
